<?php

namespace api\ygzc\model;

use think\Model;

class WxPushModel extends Model
{	
	private $appId = 'wx3b8782119613a919';
    private $appSecret ='7ad09ba4170fdd520776a7ccf7140ac2';
    
    /**模板消息**/
    function tsmbmsg($openid,$order_sn){
        $access_token = $this->getToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;
        $post_string = array(
                'touser'=>$openid,
                'template_id'=>'w3KpcE9Y1ly0Dihm9yrxXNP8WwDCjzuxIFDLw45z7g4',
                'url'=>'',
                'data'=>array(
                    'first'=>array('value'=>'您好，您有新的订单,请到政采商城上查看'),    
                    'keyword1'=>array('value'=>$order_sn),                     
                    'keyword2'=>array('value'=>date('Y-m-d H:i',time())),
                    'remark'=>array('value'=>'请及时处理。'),
                )
        );
        $data = json_encode($post_string);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_URL,$url);
        //为了支持cookie
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        //返回结果
        //拒绝验证ca证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close ($ch);
        return $result;    
        
    }
	
	
	//**获取ACCESS_TOKEN**
    function getToken(){
        $file = './upload/accesstoken.txt'; //用于保存access token
        $is_true = false;
        if(file_exists($file)){ //判断文件是否存在
            $content = file_get_contents($file); //获取文件内容
            $content = json_decode($content);//json解码
            if(isset($content->expires_in)){
                if(time()-filemtime($file)<$content->expires_in){ //判断文件是否过期
                    $is_true = true;
    				return $content->access_token;
                }
            }
        }
        if($is_true == false){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appId."&secret=".$this->appSecret;
    		$ch = curl_init();
    		curl_setopt($ch, CURLOPT_URL,$url);
    		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
    		$data = curl_exec($ch);
    		curl_close($ch);
    		file_put_contents($file, $data);
    		$content = json_decode($data);//进行json解码
		    return $content->access_token;//返回access token
        }
    }

}